package com.meng.baselibrary.adapter;

import android.content.Context;
import android.support.v4.util.SparseArrayCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 *  支持addHeaderView、addFooterView
 *  支持对item的单击监听  setOnItemClickListener
 *  支持多类型的item布局(tyle直接用layout的id表示)
 */
public abstract class BaseRecycleViewAdapter<T> extends RecyclerView.Adapter{
    private static final int BASE_ITEM_TYPE_HEADER = 1024;
    private static final int BASE_ITEM_TYPE_FOOTER = 2048;

    private SparseArrayCompat<View> mHeaderViews = new SparseArrayCompat<>();
    private SparseArrayCompat<View> mFooterViews = new SparseArrayCompat<>();
    private List<T> datas = new ArrayList<>();
    private LayoutInflater inflater;
    private Context context;
    public List<T> getDatas() {
        return datas;
    }
    public void setDatas(List<T> datas){
        this.datas.clear();
        this.datas.addAll(datas);
        this.notifyDataSetChanged();
    }
    public void addDatas(List<T> datas){
        this.datas.addAll(datas);
        this.notifyDataSetChanged();
    }
    /**
     * 局部刷新
     * @param position item的位置不包括header
     */
    public void notifyRealItemChanged(int position){
        super.notifyItemChanged(position+getHeaderViewCount());
    }
    public void clearDatas(){
        datas.clear();
        notifyDataSetChanged();
    }
    public T getItem(int position){
        return datas.get(position);
    }
    protected View inflaterView(int layoutRes, ViewGroup viewGroup){
        return getInflater().inflate(layoutRes,viewGroup,false);
    }
    public LayoutInflater getInflater() {
        return inflater;
    }
    public Context getContext() {
        return context;
    }
    public void addHeaderView(View view){
        if(mHeaderViews.indexOfValue(view) == -1){
            mHeaderViews.put(BASE_ITEM_TYPE_HEADER + mHeaderViews.size(),view);
        }
    }
    public void addFooterView(View view){
        if(mFooterViews.indexOfValue(view) == -1){
            mFooterViews.put(BASE_ITEM_TYPE_FOOTER + mFooterViews.size(),view);
        }
    }
    public int getHeaderViewCount(){
        return mHeaderViews.size();
    }
    public int getFooterViewCount(){
        return mFooterViews.size();
    }
    public BaseRecycleViewAdapter(Context context) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
    }
    @Override
    public int getItemViewType(int position) {
        if(isHeaderView(position)){
            return mHeaderViews.keyAt(position);
        }else if(isFooterView(position)){
            return mFooterViews.keyAt(position - getHeaderViewCount() - datas.size());
        }
        return getItemViewLayout(position - getHeaderViewCount());
    }
    protected abstract int getItemViewLayout(int position);
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(mHeaderViews.get(viewType) != null){
            return new RecyclerView.ViewHolder(mHeaderViews.get(viewType)) {
            };
        }else if(mFooterViews.get(viewType) != null){
            return new RecyclerView.ViewHolder(mFooterViews.get(viewType)) {
            };
        }else{
            return onCreateItemViewHolder(parent,viewType);
        }
    }

    protected abstract RecyclerView.ViewHolder onCreateItemViewHolder(ViewGroup parent, int viewType);
    protected abstract void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position);
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(isHeaderView(position) || isFooterView(position)){
            return;
        }
        onBindItemViewHolder(holder,position-getHeaderViewCount());
    }

    /**
     * 判断该位置是否是header
     * @param position
     * @return
     */
    private boolean isHeaderView(int position){
        return position < getHeaderViewCount();
    }

    /**
     * 判断该位置是否是footer
     * @param position
     * @return
     */
    private boolean isFooterView(int position){
        return position >= getHeaderViewCount()+datas.size();
    }
    @Override
    public int getItemCount() {
        return getHeaderViewCount()+datas.size()+getFooterViewCount();
    }

    protected class BaseViewHolder extends RecyclerView.ViewHolder{

        public BaseViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    if(onItemClickListener != null){
                        int realPos = getAdapterPosition()-getHeaderViewCount();
                        T bean =  getItem(realPos);
                        onItemClickListener.onItemClick(getAdapterPosition(),realPos,v,bean);
                    }
                }
            });
        }
    }
    public interface OnItemClickListener<T>{
        /**
         * @param recycleViewPosition 算上头部
         * @param itemDataPosition  不算头部
         * @param view
         * @param data
         */
        void onItemClick(int recycleViewPosition, int itemDataPosition, View view, T data);
    }
    private OnItemClickListener onItemClickListener;
    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }

    /**
     * 重写该方法 当recyclerView的LayoutManager为GridLayoutManager时，
     * 让head和footer占一整行
     * @param recyclerView
     */
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if(layoutManager instanceof GridLayoutManager){
            final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return isHeaderView(position) || isFooterView(position)
                            ? gridLayoutManager.getSpanCount() : 1;
                }
            });
        }
    }

    /**
     * StaggeredGridLayoutManager中并没有像GridLayoutManager
     * 设置占多少单元格的方法，所以在onViewAttachedToWindow方法中来处理
     * @param holder
     */
    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        int position = holder.getLayoutPosition();
        if(isHeaderView(position) || isFooterView(position)){
            ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
            if(lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams){
                StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) lp;
                params.setFullSpan(true);
            }
        }
    }
}
